<template>
  <div class="file-matching_wrapper">
    <h3>
      <h5>选择模版</h5>
      <mds-tag
        :color="'#0364FF'"
        v-for="item in templateList"
        :key="item.name"
        @click.native="setFormLabelAlignByTemplate(item)"
      >
        {{ item.name }}
        <mds-icon
          v-if="!item.sys"
          type="line-delete"
          style="color: red; margin-left: 8px"
          @click.native.stop.prevent="deleteConfig(item)"
        />
      </mds-tag>
    </h3>
    <el-form
      ref="ruleForm"
      label-position="top"
      :model="formLabelAlign"
      :rules="rules"
    >
      <el-form-item label="搜索" prop="regular">
        <el-input
          v-model="formLabelAlign.regular"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 12 }"
          placeholder="请输入  换行分割"
          clearable
          style="width: 75%"
        ></el-input>
      </el-form-item>
      <el-form-item label="扫描文件路径" prop="path">
        <el-input v-model="formLabelAlign.path" clearable style="width: 75%">
          <i
            slot="suffix"
            class="el-input__icon el-icon-folder"
            style="cursor: pointer;"
            @click="handleGetPath()"
          >
          </i>
        </el-input>
      </el-form-item>
      <el-form-item label="要包含的文件" prop="includes">
        <el-input
          v-model="formLabelAlign.includes"
          clearable
          style="width: 75%"
        ></el-input>
      </el-form-item>
      <el-form-item label="排除的文件" prop="excludes">
        <el-input
          v-model="formLabelAlign.excludes"
          clearable
          style="width: 75%"
        ></el-input>
      </el-form-item>
      <el-form-item label="输出文件存储路径" prop="outPath">
        <el-input v-model="formLabelAlign.outPath" clearable style="width: 75%">
          <i
            slot="suffix"
            class="el-input__icon el-icon-folder"
            style="cursor: pointer;"
            @click="handleGetPath('outPath')"
          >
          </i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >搜索</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="saveConfig('ruleForm')">保存配置</el-button>
      </el-form-item>
    </el-form>
    <mds-modal
      :visibility.sync="saveConfigInfo.visibility"
      title="标题"
      @ok="saveConfigInfo.handleOk"
    >
      <div class="block">
        <mds-input
          placeholder="请输入配置名称"
          v-model="saveConfigInfo.value"
        ></mds-input>
      </div>
    </mds-modal>
  </div>
</template>

<script>
import FileMatching from "../utils/fileMatching";

const localInfoName = "LOCAL_INFO_NAME_BY_TOOKIT";

const templateList = [
  {
    name: "清空",
    sys: true,
    param: {
      regular: "",
      path: "",
      outPath: "",
      includes: "",
      excludes: "",
    },
  },
  {
    name: "el-*",
    sys: true,
    param: {
      regular: [
        "<el-*",
        "<el-form/-*",
        "<el-input",
        "<el-select",
        "<el-option",
        "<el-table",
        "<el-radio",
        "<el-date-picker",
        "<el-checkbox",
        "<el-tooltip",
        "<el-button",
        "<el-cascader",
        "<el-tabs",
        "<el-tab-pane",
        "<el-col",
        "<el-row",
        "<el-dialog",
        "<el-dropdown",
        "<el-tree",
        "<el-upload",
        "<el-collapse",
        "<el-popover",
        "<el-drawer",
        "<el-pagination",
        "<el-icon",
        "<el-time-picker",
        "<el-tooltip",
        "<el-switch",
        "<el-autocomplete"
      ].join("\n"),
      includes: "\\.vue",
      excludes: "\/node_modules|\/\.git|\/\.history|\/dist|\/tests",
    },
  },
  {
    name: "mds-*",
    sys: true,
    param: {
      regular: [
        "<mds-*",
        "<mds-icon",
        "<mds-button",
        "<mds-link",
        "<mds-breadcrumb",
        "<mds-menu",
        "<mds-pagination",
        "<mds-dropdown",
        "<mds-steps",
        "<mds-input",
        "<mds-inputnumber",
        "<mds-rate",
        "<mds-radio",
        "<mds-checkbox",
        "<mds-select",
        "<mds-cascader",
        "<mds-switch",
        "<mds-time-picker",
        "<mds-date-picker",
        "<mds-slider",
        "<mds-form",
        "<mds-upload",
        "<mds-transfer",
        "<mds-tabs",
        "<mds-table",
        "<mds-tree",
        "<mds-tooltip",
        "<mds-popover",
        "<mds-timeline",
        "<mds-empty",
        "<mds-modal",
        "<mds-drawer",
        "<mds-transition",
      ].join("\n"),
      includes: "\\.vue",
      excludes: "\/node_modules|\/\.git|\/\.history|\/dist|\/tests",
    },
  },
  {
    name: "a-*",
    sys: true,
    param: {
      regular: [
        "<a-*",
        "<a-select",
        "<a-divider",
        "<a-progress"
      ].join("\n"),
      includes: "\\.vue",
      excludes: "\/node_modules|\/\.git|\/\.history|\/dist|\/tests",
    },
  },
];

export default {
  name: "file-matching-page",
  data() {
    return {
      templateList,
      rules: {
        regular: [
          { required: true, message: "请输入正则表达式", trigger: "change" },
        ],
        path: [
          { required: true, message: "请输入搜索文件路径", trigger: "change" },
        ],
      },
      formLabelAlign: {
        regular: "",
        path: "",
        outPath: "",
        includes: "",
        excludes: "",
      },
      saveConfigInfo: {
        visibility: false,
        handleOk: () => {},
        value: "",
      },
    };
  },
  created() {
    this.updatetTmplateList();
  },
  methods: {
    updatetTmplateList() {
      let localInfo = JSON.parse(
        localStorage.getItem(localInfoName) || JSON.stringify([])
      );
      localInfo = templateList.concat(localInfo);
      console.log(localInfo);
      this.templateList = localInfo;
    },
    async handleGetPath(key = 'path') {
      const { dialog } = require("electron").remote;
      const res = await dialog.showOpenDialog({
        title: "选择文件夹路径",
        properties: [
          "openDirectory",
          "showHiddenFiles",
          "dontAddToRecent",
          "treatPackageAsDirectory",
        ],
      });
      if (res && res[0]) {
        this.formLabelAlign[key] = res[0];
      } else {
        this.formLabelAlign[key] = "";
      }
    },
    setFormLabelAlignByTemplate(item) {
      const { param } = item;
      this.formLabelAlign = {
        ...this.formLabelAlign,
        ...param,
      };
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "匹配中...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          const { regular, path, includes, excludes, outPath } = this.formLabelAlign;
          const data = FileMatching(regular, path, includes, excludes, outPath);
          loading.close();
          if (data) {
            this.$message({
              content: `匹配完成！已保存到${data.filename || ""}文件中`,
              showClose: true,
              type: "success",
            });
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    saveConfig(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveConfigInfo = {
            visibility: true,
            handleOk: this.saveConfigHandle,
            value: "",
          };
        } else {
          this.$message({
            content: "请填写完整",
            showClose: true,
            type: "error",
          });
          return false;
        }
      });
    },
    saveConfigHandle() {
      const { value } = this.saveConfigInfo;
      if (!value) {
        this.$message({
          content: "请填写配置名称",
          showClose: true,
          type: "error",
        });
        return;
      }
      const { templateList } = this;
      const item = templateList.find((i) => i.name === value);
      if (item) {
        this.$message({
          content: "配置名称重复，请重新填写",
          showClose: true,
          type: "error",
        });
        return;
      }
      const { regular, includes, excludes, path, outPath } = this.formLabelAlign;
      const info = {
        name: value,
        param: {
          path,
          outPath,
          regular,
          includes,
          excludes,
        },
      };
      let localInfo = JSON.parse(
        localStorage.getItem(localInfoName) || JSON.stringify([])
      );
      localInfo.unshift(info);
      localInfo = localInfo.filter((i) => !i.sys);
      localStorage.setItem(localInfoName, JSON.stringify(localInfo));
      this.$message({
        content: "配置保存成功",
        showClose: true,
        type: "success",
      });
      this.saveConfigInfo.visibility = false;
      this.updatetTmplateList();
    },
    deleteConfig(item) {
      this.$msgbox({
        title: `是否删除 ${item.name}？`,
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then((action) => {
        if (action === "confirm") {
          const { name } = item;
          let { templateList } = this;
          templateList = JSON.parse(JSON.stringify(templateList));
          const itemIndex = templateList.findIndex((i) => i.name === name);
          if (itemIndex !== -1) {
            templateList.splice(itemIndex, 1);
            templateList = templateList.filter((i) => !i.sys);
            localStorage.setItem(localInfoName, JSON.stringify(templateList));
            this.$message({
              content: "删除成功",
              showClose: true,
              type: "success",
            });
            this.updatetTmplateList();
          } else {
            this.$message({
              content: "删除失败，请稍后再试",
              showClose: true,
              type: "error",
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.file-matching_wrapper {
  height: 100%;
  color: #000;
  h3 {
    padding: 12px 0 20px 0;
    h5 {
      font-size: 14px;
      padding-bottom: 12px;
    }
  }
}
</style>
